package com.ke.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.ke.pojo.BaseResp;
import com.ke.service.AliPayService;
import com.ke.utils.AliPayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * @author bochen
 */
@RestController
@RequestMapping("/ali")
@CrossOrigin(allowCredentials = "true")
public class AliPayController {
    @Autowired
    AliPayService aliPayService;
    @RequestMapping("/pay")
    public String pay(@RequestBody Map<String, Object> map, HttpServletRequest request){
        List<Integer> list= (List<Integer>) map.get("ids");
        Integer uid=new Integer((String)request.getAttribute("id"));
        return aliPayService.pay(list,uid);
    }
    @RequestMapping("/notifyPay")
    public void notifyPay(HttpServletRequest request) throws AlipayApiException {
        //将异步通知中收到的所有参数都存放到 map 中
        Map<String, String> paramsMap = AliPayUtils.convertRequestParamsToMap(request);
        //调用SDK验证签名
        boolean  signVerified = AlipaySignature.rsaCheckV1(paramsMap,"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAptdiZuYU+sZkfs3h6r1aFCzcXtHuuK/ZV43fZlqREGBGt7MFiKI5RU7frCmcJtUnHawsFiz6zv/og3Xi/LmegLlBZQ5V6/u+fPE13+wujgDe4TR+Wh87v0ZBMHZwIwIUIT3Y8p/MgWOuVIpWeI7QovpCTrSKz9Jg5EnlbAKnnVcrwwy59UZjhteCYZJ2ob91Au3dzNHlEwy4p7VLMlNKSV6EBdq4YeXouTYyXxemM7roYDGt3rVtFmo9/zA3oZXz1Klcif6oEDn06i9b7xYEgFVrJb8s8SJ7Hwg9oVXNg0EDCB6XoD90yDliHJ2QIkwtPjTlJIsQaHLxiCKH4A8SuwIDAQAB","utf-8","RSA2");
        if (signVerified){
            // TODO 验签成功后，按照支付结果异步通知中的描述，对支付结果中的业务内容进行二次校验，校验成功后在response中返回success并继续商户自身业务处理，校验失败返回failure
            //获取订单号与订单状态去数据库改变订单状态
            String uuid = paramsMap.get("out_trade_no");
            String status = paramsMap.get("trade_status");
            aliPayService.updateStatus(uuid,status);
        } else {
            // TODO 验签失败则记录异常日志，并在response中返回failure.
        }
    }
}
